package com.baizhi.product.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.aliyun.oss.OSS;
import com.baizhi.entity.ResultEntity;
import com.baizhi.product.config.OSSConfig;
import com.baizhi.product.entity.Brand;
import com.baizhi.product.entity.CategoryBrandRelation;
import com.baizhi.product.service.IBrandService;
import com.baizhi.product.service.ICategoryBrandRelationService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhangsan
 * @since 2022-03-23
 */
@RestController
@RequestMapping("/brand")
public class BrandController {
    @Autowired
    private OSS client;
    @Value("${bulkName}")
    private String bulkName;
    @Autowired
    private IBrandService bs;
    @Autowired
    private ICategoryBrandRelationService cbrs;
    @SneakyThrows
    @PostMapping("/uploadImg")
    public ResultEntity uploadImg(MultipartFile brandImg){
        String oldName = brandImg.getOriginalFilename();//获取到上传文件的原始文件名
        String newName = UUID.randomUUID().toString()+oldName;//给图片新换一个名字
        client.putObject(bulkName, newName, brandImg.getInputStream());
        String result="https://"+bulkName+"."+ OSSConfig.ENDPOINT+"/"+newName;
        return ResultEntity.ok(result);
    }

    @PostMapping("/add")
   public ResultEntity add(@RequestBody Brand brand){
        bs.save(brand);
        return ResultEntity.ok();
    }
    //做excel的导出功能,参数就是接收我们excel表格的响应对象
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws Exception {
        //指定response的响应格式是一个附件
        response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode("所有品牌.xls","utf-8"));
        //把excel表格交给response进行响应
        //获取到所有的品牌信息
        List<Brand> list = bs.list();
        //把品牌信息通过excel工具类进行导出
        ExportParams params=new ExportParams("所有品牌列表","brands");
        Workbook workbook = ExcelExportUtil.exportExcel(params, Brand.class, list);
        //把excel表格写到了response的流里面
        workbook.write(response.getOutputStream());
    }
    @PostMapping("/importExcel")
    //根据excel表格的数据进行导入,参数就是前端传来的excel文件
    public ResultEntity importExcel(MultipartFile excelFile) throws Exception {
        //指定这个excel的基本设置
        ImportParams params=new ImportParams();
        //指定excel表格的标题只有一行
        params.setTitleRows(1);
        //指定excel的表格的表头有一行
        params.setHeadRows(1);
        //导入,返回一个list集合，这个集合里面存放的就是我们excel表格里面的品牌数据
        List<Brand> brandList = ExcelImportUtil.importExcel(excelFile.getInputStream(), Brand.class, params);
        bs.saveBatch(brandList);
        return ResultEntity.ok("批量插入成功");
    }
    @GetMapping("/selectBrandByCategoryId/{categoryId}")
    public ResultEntity selectBrandByCategoryId(@PathVariable("categoryId") int categoryId){
        QueryWrapper<CategoryBrandRelation> wrapper=new QueryWrapper<>();
        wrapper.eq("category_id",categoryId);
        List<CategoryBrandRelation> list = cbrs.list(wrapper);
        List<Long> brandIds = list.stream().map((cbr) -> {
            return cbr.getBrandId();
        }).collect(Collectors.toList());
        return ResultEntity.ok(bs.listByIds(brandIds));
    }
}

